#include <iostream>
#include <string>
#include <vector>
#include <cstdio>
#include <pthread.h>
#include <unistd.h>

using namespace std;
int tickets = 50;
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t cond = PTHREAD_COND_INITIALIZER;

void* start_routine(void* args)
{
    string name = static_cast<const char*> (args);

    while(true)
    {
        pthread_mutex_lock(&mutex);
        
        //但是当一个线程调用 pthread_cond_wait 时，锁会被自动释放，并且线程会进入等待状态。
        //直到有其他线程调用 pthread_cond_signal 或 pthread_cond_broadcast 唤醒它时，锁才会被重新获取。
        pthread_cond_wait(&cond, &mutex);

        if (tickets <= 0) 
        {
            pthread_mutex_unlock(&mutex);
            break;
        }
        
        cout << name << " -> " << tickets << endl;
        tickets--;

        pthread_mutex_unlock(&mutex);

    }
}

int main()
{
    vector<pthread_t> v(5);
    // pthread_t t[2];
    for(int i = 0; i < 5; ++i)
    {
        char* name = new char[64];
        snprintf(name, 64, "thread->%d", i+1);
        pthread_create(&v[i], nullptr, start_routine, (void*)name);
        // pthread_create(&t[i], nullptr, start_routine, (void*)name);
    }
    
    while(true)
    {
        sleep(1);
        // pthread_cond_signal(&cond);
        // 唤醒一批线程
        pthread_cond_broadcast(&cond);
        cout << "main thread wakeup ..." << endl;
    }

    for(const auto& tid : v)
    {
        pthread_join(tid,nullptr);
    }

    return 0;
}